package com.ls.servlet.user;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.ls.pojo.Role;
import com.ls.pojo.User;
import com.ls.service.role.RoleServiceImpl;
import com.ls.service.user.UserService;
import com.ls.service.user.UserServiceImpl;
import com.ls.util.PageSupport;
import com.ls.util.constant.Constant;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author 李朔
 * @version 1.0
 */
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method!=null && method.equals("savepwd")){
            this.updatePwd(req,resp);
        }else if(method.equals("pwdmodify")){
            this.pwdModify(req,resp);
        }else if(method.equals("query")){
            try {
                this.query(req,resp);
            } catch (Exception throwables) {
                throwables.printStackTrace();
            }
        }else if(method.equals("add")){
            //增加用户
            try {
                this.add(req,resp);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }else if(method != null && method.equals("ucexist")){
            try {
                this.userCodeExist(req, resp);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    public void userCodeExist(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException {
        //判断用户账号是否可用
        String userCode = req.getParameter("userCode");
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (userCode != null) {
            //userCode == null || userCode.equals("")
            resultMap.put("userCode", "exist");
        } else {
            UserService userService = new UserServiceImpl();
            User user = userService.selectUserCodeExist(userCode);
            if (null != user) {
                resultMap.put("userCode", "exist");
            } else {
                resultMap.put("userCode", "notexist");
            }

        }
        //把resultMap转为json字符串以json的形式输出
        //配置上下文的输出类型
        resp.setContentType("application/json");
        //从response对象中获取往外输出的writer对象
        PrintWriter outPrintWriter = resp.getWriter();
        //把resultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();//刷新
        outPrintWriter.close();//关闭流
    }

    //添加用户操作
    public void add(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException, ServletException {
        System.out.println("add...............");
        //从前端中获取信息
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user=new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);


        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (Exception e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)req.getSession().getAttribute(Constant.USER_SESSION)).getId());

        UserService userService=new UserServiceImpl();
        if(userService.addUser(user)){
            resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
        }else{
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);
        }
    }
    //重点，难点
    public void query(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ClassNotFoundException, ServletException, IOException {
        //查询用户列表
        //从前端获取数据
        String queryname = req.getParameter("queryname");//要查询的用户的名字
        String queryUserRole = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int userRole=0;

        //获取用户列表
        List<User> userList=null;
        UserServiceImpl userService = new UserServiceImpl();
        //第一次走这个请求，一定是第一页，页面大小固定
        int pageSize=5;//建议写到配置文件中，方便后期修改
        int currentPageNo=1;

        if(queryname==null){
            //查询的名字是空
            queryname="";
        }
        if(queryUserRole!=null && !queryUserRole.equals("")){
            userRole=Integer.parseInt(queryUserRole);//给查询赋值
        }
        if(pageIndex!=null){
            currentPageNo=Integer.parseInt(pageIndex);
        }
        //获取用户的总数(分页：上一页，下一页)
        int userTotalCount = userService.getUserCount(queryname, userRole);
        //总页数支持
        PageSupport pageSupport=new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(userTotalCount);
        int totalPageCount = pageSupport.getTotalPageCount();
        //控制首页和尾页
        //如果页面要小于1了，就返回1
        if(currentPageNo<1){
            currentPageNo=1;
        }else if(currentPageNo>totalPageCount){
            //当前页面大于了最后一页
            currentPageNo=userTotalCount;
        }

        //获取用户列表展示
        userList = userService.getUserList(queryname, userRole, currentPageNo, pageSize);
        req.setAttribute("userList",userList);


        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList=roleService.getRoleList();
        req.setAttribute("roleList",roleList);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("totalCount",userTotalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("queryUserName",queryname);
        req.setAttribute("queryUserRole",userRole);
        //返回前端
        req.getRequestDispatcher("/jsp/userlist.jsp").forward(req,resp);
    }
    //修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //从Session里面拿ID；
        Object o = req.getSession().getAttribute(Constant.USER_SESSION);
        //从前端拿参数
        String newpassword = req.getParameter("newpassword");
        boolean flag=false;
        if(o!=null && newpassword!=null){
            User user=(User) o;
            UserService userService=new UserServiceImpl();
            try {
                flag=userService.updatePwd( user.getId(),newpassword);
                if(flag){
                    req.setAttribute("message","修改密码成功，请退出，使用新密码登录");
                    //密码修改成功，移除当前Session
                    req.getSession().removeAttribute(Constant.USER_SESSION);
                }else{
                    req.setAttribute("message","密码修改失败");
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }else{
            req.setAttribute("message","新密码有问题");
        }
        //页面跳转
        req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
    }
    //验证旧密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        Object o=req.getSession().getAttribute(Constant.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");
        //使用Map进行传参,一切的东西都可以存到map里面
        HashMap<String,String> resultMap=new HashMap<String,String>();
        if(o==null){
            //Session失效了，Session过期了
            resultMap.put("result","sessionerror");
        }else if(oldpassword==null || oldpassword.equals("")){
            //输入密码为空
            resultMap.put("result","error");
        }else{
            User user=(User) o;
            String userPassword = user.getUserPassword();//Session中的用户密码
            if(oldpassword.equals(userPassword)){
                resultMap.put("result","true");
            }else{
                resultMap.put("result","false");
            }
        }
        try {
            resp.setContentType("application/json");
            PrintWriter writer=resp.getWriter();
            //JSONArray 阿里巴巴的JSON工具类,转换格式
            /*
            * resultMap=["result","sessionerror","result","error"]
            * 转换成Json格式={key:value}
            * */
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
